from datetime import datetime, timedelta

class RouteRecommender:
    def __init__(self):
        from config import HAIKOU_SPOTS
        self.haikou_spots = HAIKOU_SPOTS

    def generate_route(self, selected_interests, budget, time, route_type):
        # 根据兴趣筛选景点
        filtered_places = []
        for category in selected_interests:
            filtered_places.extend(self.haikou_spots.get(category, []))
        
        # 添加预算过滤
        affordable_places = []
        for place in filtered_places:
            cost = place.get("duration", 0)*50
            if cost <= float(budget):
                affordable_places.append(place)
        
        # 按距离排序（简化版）
        current_location = "110.3434,20.0456"
        sorted_places = sorted(affordable_places, 
            key=lambda x: self._distance(x["location"], current_location))
        
        # 时间过滤
        selected_places = []
        total_time = 0
        for place in sorted_places:
            duration = place.get("duration", 0)
            if total_time + duration <= float(time):
                selected_places.append(place)
                total_time += duration
        
        # 生成每日计划
        days = 1
        daily_budget = float(budget)/days  # 简化为1天行程
        daily_plan = []
        current_time = datetime.strptime("09:00", "%H:%M")
        for idx, place in enumerate(selected_places):
            arrival = current_time.strftime("%H:%M")
            departure = (current_time + timedelta(hours=place["duration"])).strftime("%H:%M")
            daily_plan.append({
                "name": place["name"],
                "arrival": arrival,
                "departure": departure,
                "location": place["location"]
            })
            current_time += timedelta(hours=place["duration"] + 0.5)  # 加交通时间
        
        route_description = f"预算：{budget}元，兴趣：{','.join(selected_interests)}，时间：{time}小时\n推荐路线：\n"
        for day in daily_plan:
            route_description += f"{day['arrival']}-{day['departure']} {day['name']} \n"
        
        locations = [p["location"] for p in selected_places]
        
        # 计算费用
        cost_breakdown = f"餐饮：{daily_budget*0.6:.0f}元 | 交通：{daily_budget*0.3:.0f}元 | 门票：{daily_budget*0.1:.0f}元/天"
        
        return route_description, locations, selected_places, cost_breakdown

    def _distance(self, loc1, loc2):
        # 简化版距离计算
        x1,y1 = map(float, loc1.split(','))
        x2,y2 = map(float, loc2.split(','))
        return (x1-x2)**2 + (y1-y2)**2